home *** CD-ROM | disk | FTP | other *** search
/ Atari Mega Archive 1 / Atari Mega Archive - Volume 1.iso / gnu / progutil / stdwin.zoo / test / bsdsetdate.c < prev    next >
Encoding:
C/C++ Source or Header  |  1989-10-17  |  1.5 KB  |  60 lines

  1. /* Set the date and time -- 4.3 BSD Unix version */
  2.  
  3. /* This file is #included in klok.c, hence there are no #includes.
  4.    It would need at least <sys/times.h>. */
  5.  
  6. #define isleap(y) ((y)%4 == 0 && ((y)%100 != 0 || (y)%400 == 0))
  7.  
  8. /* Convert a struct tm to seconds since Jan. 1, 1970.
  9.    This knows nothing about time zones or daylight saving time. */
  10.  
  11. static unsigned long
  12. tm2tv(tp)
  13.     struct tm *tp;
  14. {
  15.     static short mdays[12]=
  16.         {31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  17.     unsigned long s= 0;
  18.     int y, m, d;
  19.     
  20.     for (y= 1970; y < tp->tm_year + 1900; ++y) {
  21.         s += 365;
  22.         if (isleap(y))
  23.             ++s;
  24.     }
  25.     mdays[1]= 28 + isleap(y); /* Months have origin 0 */
  26.     for (m= 0; m < tp->tm_mon; ++m)
  27.         s += mdays[m];
  28.     s += tp->tm_mday - 1;
  29.     return ((s*24 + tp->tm_hour)*60 + tp->tm_min)*60 /*+ tp->tm_sec*/;
  30. }
  31.  
  32. /* Set the date and time from a struct tm.
  33.    The Input time is in local time.
  34.    If 'minchange' is zero, minutes and seconds are not taken
  35.    from the input but from the current system time. */
  36.  
  37. setdatetime(tp, minchange)
  38.     struct tm *tp;
  39.     int minchange; /* nonzero if we must reset minutes and seconds, too */
  40. {
  41.     struct timeval tv;
  42.     struct timezone tz;
  43.     unsigned long t;
  44.     
  45.     t= tm2tv(tp);                /* t is local time */
  46.     if (gettimeofday(&tv, &tz) != 0)
  47.         return -1;
  48.     if (tp->tm_isdst)
  49.         t -= 3600;            /* t is local time less DST */
  50.     t += tz.tz_minuteswest*60;        /* t is GMT time */
  51.     if (minchange)
  52.         t= t/60 * 60;            /* Clear seconds */
  53.     else
  54.         t= t/3600 * 3600 + tv.tv_sec % 3600; /* Use current min/sec */
  55.     tv.tv_sec= t;
  56.     if (settimeofday(&tv, &tz) != 0)
  57.         return -1;
  58.     return 0;
  59. }
  60.